<template>
  <el-row :gutter="10" type="flex" justify="center">
    <el-col :md="8">
      <el-card class="box-card" style="margin-top: 30%">
        <div slot="header">
          <span>用户登录</span>
        </div>
        <el-form
          ref="ruleForm"
          v-loading.body="loading"
          label-width="80px"
          :model="user"
          :rules="rules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="user.username"
              @keyup.enter.native="submit"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="user.password"
              type="password"
              @keyup.enter.native="submit"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit()">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>
<script>
export default {
  data() {
    return {
      redirect: undefined,
      otherQuery: {},
      loading: false,
      user: {
        username: 'lendoo',
        password: 'lendoo'
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    submit: function() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 验证通过
          this.login()
        }
      })
    },
    login: function() {
      this.$store.dispatch('user/login', this.user)
        .then(() => {
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
        })
        .finally(() => {
          this.loading = false
        })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>
